package is.server.controller.session.remote.command;

import is.common.datatype.Request;
import is.common.exception.RowNotFoundException;
import is.common.exception.UniqueCheckFailedException;
import is.common.interfaces.Command;
import is.common.syntax.TransactionStatus;
import is.common.util.ObjectStreamer;
import is.server.Main;

import java.io.IOException;

/**
 * @author aspr0
 *         Date: 01.05.12
 *         Time: 3:53
 */
public class EditCommand implements Command
{
    private int sectionNum;
    private String[] row;
    private ObjectStreamer objectStreamer;


    public EditCommand(Request request, ObjectStreamer objectStreamer)
    {
        sectionNum = request.getSectionNum();
        row = request.getData();
        this.objectStreamer = objectStreamer;
    }


    @Override
    public void execute()
    {
        try
        {
            Main.getController().getModel().editRow(sectionNum, row);
        }
        catch (UniqueCheckFailedException e)
        {
//            e.printStackTrace();
            try
            {
                objectStreamer.transmitObject(TransactionStatus.TRANSACTION_FAILED_UNIQUE_CHECK);
            }
            catch (IOException e1)
            {
                e1.printStackTrace();
            }
            return;
        }
        catch (RowNotFoundException e)
        {
//            e.printStackTrace();
            try
            {
                objectStreamer.transmitObject(TransactionStatus.TRANSACTION_FAILED_ROW_NOT_FOUND);
            }
            catch (IOException e1)
            {
                e1.printStackTrace();
            }
            return;
        }

        try
        {
            objectStreamer.transmitObject(TransactionStatus.TRANSACTION_OK);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
